package com.petadoption.serverclient.interceptor;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.petadoption.serverclient.config.AuthAccess;
import com.petadoption.serverclient.entity.User;
import com.petadoption.serverclient.exception.ServiceException;
import com.petadoption.serverclient.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//Jwt拦截器
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) token = request.getParameter("token");
        if (handler instanceof HandlerMethod) {
            AuthAccess authAccess = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (authAccess != null) return true;
        }

        if (StrUtil.isBlank(token)) throw new ServiceException("401", "请登录");

        //获取token信息
        Integer userId;
        try {
            userId = Integer.valueOf(JWT.decode(token).getAudience().get(0));
            System.out.println("token解析出来的用户ID:" + userId);
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }

        //根据id查询数据库
//        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", userId));
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new ServiceException("401", "请登录");
        }
        //用户密码加签名验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserPassword())).build();
        try {
            jwtVerifier.verify(token);//验证token
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }

        return true;
    }

}
